package logic

import (
	"context"
	"errors"
	"yim_server/yim_file/file_models"

	"yim_server/yim_file/file_rpc/internal/svc"
	"yim_server/yim_file/file_rpc/types/file_rpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UploadFileLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUploadFileLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UploadFileLogic {
	return &UploadFileLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// UploadFile 将文件记录保存在数据库中
func (l *UploadFileLogic) UploadFile(in *file_rpc.UploadFileRequest) (*file_rpc.UploadFileResponse, error) {
	var file file_models.FileModels

	file = file_models.FileModels{
		FileName:      in.Name,
		FileType:      in.Type,
		FileUrl:       in.Url,
		UserId:        uint(in.UserId),
		FileHash:      in.Hash,
		FileSize:      in.Size,
		FileExtension: in.Extension,
	}

	err := l.svcCtx.DB.Create(&file).Error
	if err != nil {
		logx.Error(err)
		return nil, errors.New("文件保存失败")
	}

	return &file_rpc.UploadFileResponse{Hash: in.Hash}, nil
}
